<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>电商平台 - 首页</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .category-nav {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 15px;
        }
        .category-item {
            padding: 5px 0;
            cursor: pointer;
        }
        .category-item:hover {
            color: #0d6efd;
        }
        .subcategory {
            padding-left: 20px;
            display: none;
        }
        .product-card {
            transition: all 0.3s ease;
            margin-bottom: 20px;
            height: 100%;
        }
        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .product-img {
            height: 180px;
            object-fit: contain;
            padding: 10px;
        }
        .cart-sidebar {
            position: fixed;
            top: 0;
            right: -400px;
            width: 400px;
            height: 100%;
            background: white;
            box-shadow: -2px 0 5px rgba(0,0,0,0.1);
            transition: right 0.3s ease;
            z-index: 1050;
            padding: 20px;
            overflow-y: auto;
        }
        .cart-sidebar.show {
            right: 0;
        }
        .cart-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1040;
            display: none;
        }
        .cart-overlay.show {
            display: block;
        }
        .stock-info {
            font-size: 0.8rem;
            color: #6c757d;
        }
        .shelf-life {
            font-size: 0.7rem;
            color: #dc3545;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="#">电商平台</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="#">首页</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <button id="cartBtn" class="btn btn-light position-relative">
                        <i class="bi bi-cart"></i> 购物车
                        <span id="cartBadge" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">0</span>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主内容区 -->
    <div class="container mt-4">
        <div class="row">
            <!-- 分类侧边栏 -->
            <div class="col-md-3">
                <div class="category-nav">
                    <h5>商品分类</h5>
                    <div id="categoryList">
                        <!-- 分类将通过JS动态加载 -->
                        <div class="text-center my-3">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 商品展示区 -->
            <div class="col-md-9">
                <div class="row">
                    <div class="col-12 mb-3">
                        <div class="input-group">
                            <input type="text" id="searchInput" class="form-control" placeholder="搜索商品...">
                            <button id="searchBtn" class="btn btn-outline-secondary">搜索</button>
                        </div>
                    </div>
                    
                    <div id="productList">
                        <!-- 商品将通过JS动态加载 -->
                        <div class="text-center my-5">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2">正在加载商品...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 购物车侧边栏 -->
    <div class="cart-overlay" id="cartOverlay"></div>
    <div class="cart-sidebar" id="cartSidebar">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4>我的购物车</h4>
            <button id="closeCartBtn" class="btn btn-sm btn-outline-secondary">&times;</button>
        </div>
        
        <div id="cartItems">
            <div class="text-muted text-center my-5">购物车是空的</div>
        </div>
        
        <hr>
        <div class="d-flex justify-content-between mb-2">
            <span>合计:</span>
            <span id="cartTotal">¥0.00</span>
        </div>
        <div class="d-flex justify-content-between mb-3">
            <span class="text-muted small">共 <span id="cartQuantity">0</span> 件商品</span>
        </div>
        <button id="checkoutBtn" class="btn btn-primary w-100">去结算</button>
    </div>

    <!-- 底部信息 -->
    <footer class="bg-light mt-5 py-4">
        <div class="container text-center">
            <p>&copy; 2023 电商平台 版权所有</p>
        </div>
    </footer>

    <!-- 引入脚本 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        // 全局状态
        const state = {
            cart: [],
            categories: [],
            products: []
        };

        // DOM加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 加载分类和商品
            loadCategories();
            loadProducts();

            // 设置事件监听
            document.getElementById('cartBtn').addEventListener('click', toggleCart);
            document.getElementById('closeCartBtn').addEventListener('click', toggleCart);
            document.getElementById('cartOverlay').addEventListener('click', toggleCart);
            document.getElementById('checkoutBtn').addEventListener('click', checkout);
            document.getElementById('searchBtn').addEventListener('click', searchProducts);
            document.getElementById('searchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') searchProducts();
            });
        });

        // 加载分类数据
        function loadCategories() {
            axios.get('/api/categories/')
                .then(response => {
                    state.categories = response.data;
                    renderCategories();
                })
                .catch(error => {
                    console.error('加载分类失败:', error);
                    document.getElementById('categoryList').innerHTML = '<div class="alert alert-danger">加载分类失败，请刷新重试</div>';
                });
        }

        // 渲染分类树
        function renderCategories() {
            const container = document.getElementById('categoryList');
            
            function buildCategoryTree(categories, parentId = null) {
                return categories
                    .filter(category => category.parent === parentId)
                    .map(category => {
                        const hasChildren = categories.some(c => c.parent === category.id);
                        return `
                            <div class="category-item" data-id="${category.id}">
                                ${category.name}
                                ${hasChildren ? '<i class="bi bi-chevron-down float-end"></i>' : ''}
                                <div class="subcategory">${
                                    hasChildren ? buildCategoryTree(categories, category.id) : ''
                                }</div>
                            </div>
                        `;
                    }).join('');
            }

            container.innerHTML = buildCategoryTree(state.categories);
            
            // 添加分类项点击事件
            container.querySelectorAll('.category-item').forEach(item => {
                const subcategory = item.querySelector('.subcategory');
                item.addEventListener('click', function(e) {
                    if (e.target === item || e.target.classList.contains('category-item')) {
                        if (subcategory) {
                            subcategory.style.display = subcategory.style.display === 'block' ? 'none' : 'block';
                        }
                        const categoryId = item.dataset.id;
                        filterByCategory(categoryId);
                    }
                });
            });
        }

        // 加载商品数据
        function loadProducts() {
            axios.get('/api/products/')
                .then(response => {
                    state.products = response.data;
                    renderProducts(state.products);
                })
                .catch(error => {
                    console.error('加载商品失败:', error);
                    const container = document.getElementById('productList');
                    container.innerHTML = `
                        <div class="col-12 text-center py-5">
                            <i class="bi bi-exclamation-triangle-fill text-danger fs-1"></i>
                            <h4 class="mt-3">商品加载失败</h4>
                            <button onclick="loadProducts()" class="btn btn-outline-primary mt-2">重试</button>
                        </div>
                    `;
                });
        }

        // 渲染商品列表
        function renderProducts(products) {
            const container = document.getElementById('productList');
            
            if (products.length === 0) {
                container.innerHTML = `
                    <div class="col-12 text-center py-5">
                        <i class="bi bi-box-seam text-muted fs-1"></i>
                        <h4 class="mt-3">暂无商品</h4>
                    </div>
                `;
                return;
            }

            container.innerHTML = products.map(product => `
                <div class="col-md-4 col-sm-6">
                    <div class="card product-card h-100">
                        <img src="${product.image_url || '/static/images/default-product.png'}" 
                             class="card-img-top product-img" 
                             alt="${product.name}"
                             onerror="this.src='/static/images/default-product.png'">
                        <div class="card-body">
                            <h5 class="card-title">${product.name}</h5>
                            <p class="card-text text-truncate">${product.description || '暂无描述'}</p>
                            <p class="text-danger fw-bold">¥${product.price.toFixed(2)}</p>
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="stock-info">库存: ${product.stock} ${product.unit}</span>
                                ${product.shelf_life_end_date ? 
                                    `<span class="shelf-life">保质期至: ${new Date(product.shelf_life_end_date).toLocaleDateString()}</span>` : 
                                    ''
                                }
                            </div>
                        </div>
                        <div class="card-footer bg-transparent">
                            <div class="d-grid gap-2">
                                ${product.stock > 0 ? 
                                    `<button class="btn btn-primary btn-sm add-to-cart" data-id="${product.product_code}">
                                        加入购物车
                                    </button>` : 
                                    '<button class="btn btn-secondary btn-sm disabled">已售罄</button>'
                                }
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');

            // 添加购物车按钮事件
            container.querySelectorAll('.add-to-cart').forEach(btn => {
                btn.addEventListener('click', function() {
                    const productId = this.dataset.id;
                    const product = state.products.find(p => p.product_code === productId);
                    if (product) {
                        addToCart(product);
                    }
                });
            });
        }

        // 按分类筛选商品
        function filterByCategory(categoryId) {
            const filteredProducts = state.products.filter(
                product => product.category === categoryId || 
                           isSubcategory(product.category, categoryId)
            );
            renderProducts(filteredProducts);
        }

        // 检查是否是子分类
        function isSubcategory(categoryId, parentId) {
            const category = state.categories.find(c => c.id === categoryId);
            if (!category) return false;
            if (category.parent === parentId) return true;
            if (category.parent === null) return false;
            return isSubcategory(category.parent, parentId);
        }

        // 搜索商品
        function searchProducts() {
            const keyword = document.getElementById('searchInput').value.trim().toLowerCase();
            if (!keyword) {
                renderProducts(state.products);
                return;
            }
            
            const filteredProducts = state.products.filter(product => 
                product.name.toLowerCase().includes(keyword) || 
                (product.description && product.description.toLowerCase().includes(keyword)) ||
                product.product_code.toLowerCase().includes(keyword)
            );
            
            renderProducts(filteredProducts);
        }

        // 购物车相关功能
        function toggleCart() {
            document.getElementById('cartSidebar').classList.toggle('show');
            document.getElementById('cartOverlay').classList.toggle('show');
        }

        function addToCart(product, quantity = 1) {
            const existingItem = state.cart.find(item => item.product.product_code === product.product_code);
            
            if (existingItem) {
                existingItem.quantity += quantity;
            } else {
                state.cart.push({
                    product: product,
                    quantity: quantity
                });
            }
            
            updateCart();
            showToast(`${product.name} 已添加到购物车`, 'success');
        }

        function updateCart() {
            const cartItemsEl = document.getElementById('cartItems');
            const totalPrice = state.cart.reduce((sum, item) => sum + (item.product.price * item.quantity), 0);
            const totalQuantity = state.cart.reduce((sum, item) => sum + item.quantity, 0);
            
            if (state.cart.length === 0) {
                cartItemsEl.innerHTML = '<div class="text-muted text-center my-5">购物车是空的</div>';
            } else {
                cartItemsEl.innerHTML = state.cart.map(item => `
                    <div class="cart-item mb-3">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h6>${item.product.name}</h6>
                                <small class="text-muted">${item.product.specification || ''}</small>
                            </div>
                            <span>¥${(item.product.price * item.quantity).toFixed(2)}</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mt-2">
                            <div class="input-group input-group-sm" style="width: 120px;">
                                <button class="btn btn-outline-secondary decrease-qty" data-id="${item.product.product_code}">-</button>
                                <input type="text" class="form-control text-center qty-input" value="${item.quantity}" 
                                       data-id="${item.product.product_code}">
                                <button class="btn btn-outline-secondary increase-qty" data-id="${item.product.product_code}">+</button>
                            </div>
                            <button class="btn btn-sm btn-outline-danger remove-item" data-id="${item.product.product_code}">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                `).join('');
                
                // 添加购物车项事件
                cartItemsEl.querySelectorAll('.decrease-qty').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const productId = this.dataset.id;
                        const cartItem = state.cart.find(item => item.product.product_code === productId);
                        if (cartItem && cartItem.quantity > 1) {
                            cartItem.quantity--;
                            updateCart();
                        }
                    });
                });
                
                cartItemsEl.querySelectorAll('.increase-qty').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const productId = this.dataset.id;
                        const cartItem = state.cart.find(item => item.product.product_code === productId);
                        if (cartItem) {
                            cartItem.quantity++;
                            updateCart();
                        }
                    });
                });
                
                cartItemsEl.querySelectorAll('.qty-input').forEach(input => {
                    input.addEventListener('change', function() {
                        const productId = this.dataset.id;
                        const cartItem = state.cart.find(item => item.product.product_code === productId);
                        const newQty = parseInt(this.value) || 1;
                        if (cartItem && newQty > 0) {
                            cartItem.quantity = newQty;
                            updateCart();
                        } else {
                            this.value = cartItem.quantity;
                        }
                    });
                });
                
                cartItemsEl.querySelectorAll('.remove-item').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const productId = this.dataset.id;
                        state.cart = state.cart.filter(item => item.product.product_code !== productId);
                        updateCart();
                    });
                });
            }
            
            document.getElementById('cartTotal').textContent = `¥${totalPrice.toFixed(2)}`;
            document.getElementById('cartQuantity').textContent = totalQuantity;
            document.getElementById('cartBadge').textContent = totalQuantity;
        }

        function checkout() {
            if (state.cart.length === 0) {
                showToast('购物车是空的', 'warning');
                return;
            }
            
            axios.post('/api/checkout/', {
                items: state.cart.map(item => ({
                    product_code: item.product.product_code,
                    quantity: item.quantity
                }))
            })
            .then(response => {
                showToast('订单提交成功', 'success');
                state.cart = [];
                updateCart();
            })
            .catch(error => {
                console.error('结账失败:', error);
                showToast('结账


                失败，请重试', 'error');
                updateCart();
                state.cart = [];    
                updateCart();
});
        }
        function showToast(message, type) { 
        }
        function addToCart(product, quantity = 1) {



            }
        }
        <script>
        // 显示Toast通知
        function showToast(message, type = 'info') {
            const toast = document.createElement('div');
            toast.className = `position-fixed top-0 end-0 m-3 toast show align-items-center text-white bg-${type} border-0`;
            toast.style.zIndex = '1060';
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">${message}</div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            `;
            document.body.appendChild(toast);
            
            setTimeout(() => {
                toast.classList.add('hide');
                setTimeout(() => toast.remove(), 500);
            }, 3000);
        }

        // 商品详情模态框
        function showProductDetail(productId) {
            const product = state.products.find(p => p.product_code === productId);
            if (!product) return;
            
            const modal = new bootstrap.Modal(document.getElementById('productDetailModal'));
            document.getElementById('modalProductName').textContent = product.name;
            document.getElementById('modalProductImg').src = product.image_url || '/static/images/default-product.png';
            document.getElementById('modalProductPrice').textContent = `¥${product.price.toFixed(2)}`;
            document.getElementById('modalProductCode').textContent = product.product_code;
            document.getElementById('modalProductDescription').textContent = product.description || '暂无详细描述';
            document.getElementById('modalProductStock').textContent = `${product.stock} ${product.unit}`;
            document.getElementById('modalProductSpec').textContent = product.specification || '暂无规格信息';
            document.getElementById('modalShelfLife').textContent = product.shelf_life_end_date ? 
                new Date(product.shelf_life_end_date).toLocaleDateString() : '无保质期限制';
            document.getElementById('modalAddToCart').dataset.id = product.product_code;
            
            modal.show();
        }

        // 初始化更多事件
        document.addEventListener('DOMContentLoaded', function() {
            // 添加商品点击查看详情事件
            document.getElementById('productList').addEventListener('click', function(e) {
                const card = e.target.closest('.product-card');
                if (card && !e.target.classList.contains('add-to-cart')) {
                    const productId = card.querySelector('.add-to-cart')?.dataset.id;
                    if (productId) showProductDetail(productId);
                }
            });

            // 模态框添加购物车按钮事件
            document.getElementById('modalAddToCart').addEventListener('click', function() {
                const productId = this.dataset.id;
                const product = state.products.find(p => p.product_code === productId);
                if (product) {
                    const quantity = parseInt(document.getElementById('modalQuantity').value) || 1;
                    addToCart(product, quantity);
                    bootstrap.Modal.getInstance('#productDetailModal').hide();
                }
            });
        });
    </script>

    <!-- 商品详情模态框 -->
    <div class="modal fade" id="productDetailModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalProductName">商品名称</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <img id="modalProductImg" src="" class="img-fluid rounded" alt="商品图片">
                        </div>
                        <div class="col-md-6">
                            <h3 class="text-danger" id="modalProductPrice">¥0.00</h3>
                            <hr>
                            <p id="modalProductDescription">商品描述加载中...</p>
                            <table class="table table-sm">
                                <tr>
                                    <th width="100">商品编码</th>
                                    <td id="modalProductCode"></td>
                                </tr>
                                <tr>
                                    <th>库存数量</th>
                                    <td id="modalProductStock"></td>
                                </tr>
                                <tr>
                                    <th>规格信息</th>
                                    <td id="modalProductSpec"></td>
                                </tr>
                                <tr>
                                    <th>保质期</th>
                                    <td id="modalShelfLife"></td>
                                </tr>
                            </table>
                            
                            <div class="mb-3">
                                <label for="modalQuantity" class="form-label">购买数量</label>
                                <div class="input-group" style="width: 150px;">
                                    <button class="btn btn-outline-secondary" type="button" onclick="this.nextElementSibling.stepDown()">-</button>
                                    <input type="number" class="form-control" id="modalQuantity" value="1" min="1">
                                    <button class="btn btn-outline-secondary" type="button" onclick="this.previousElementSibling.stepUp()">+</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button id="modalAddToCart" type="button" class="btn btn-primary" data-id="">加入购物车</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
</body>
</html>


